﻿namespace Harness.Commands
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using mshtml;

    internal class SelectCommand : ICommand
    {
        #region Constants

        private const int LocatorArgIndex = 0;
        private const int OptionLocatorArgIndex = 1;
        private const int BoolArgIndex = 2;

        #endregion

        #region Public Methods

        public void SyntaxCheck(IHarness harness, IEnumerable<object> args)
        {
            if (null == args.ElementAtOrDefault(LocatorArgIndex))
            {
                throw new ArgumentNullException((LocatorArgIndex + 1).ToString() + ":Locator");
            }

            if (null == args.ElementAtOrDefault(OptionLocatorArgIndex))
            {
                throw new ArgumentNullException((OptionLocatorArgIndex + 1).ToString() + ":Option");
            }
        }

        public dynamic Execute(IHarness harness, IEnumerable<object> args)
        {
            string locator = args.ElementAtOrDefault(LocatorArgIndex) as string;
            string optionLocator = (args.ElementAtOrDefault(OptionLocatorArgIndex) ?? string.Empty).ToString();

            bool b = true;

            if (!string.IsNullOrWhiteSpace(args.ElementAtOrDefault(BoolArgIndex) as string))
            {
                b = bool.Parse((args.ElementAtOrDefault(BoolArgIndex) ?? bool.TrueString).ToString());
            }

            IHTMLElement element = IE.Element.FindIfThrowNotFound(locator, IE.ActiveDocument);
            harness.HighlightElement(element, "select");
            IE.Element.SetOptionSelected(element, optionLocator, b);

            return null;
        }

        #endregion
    }
}
